package com.lj.dict.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lj.common.utils.CheckUtils;
import com.lj.common.utils.RedisUtil;
import com.lj.dict.constant.DictConstant;
import com.lj.dict.entity.Dict;
import com.lj.dict.entity.DictItem;
import com.lj.dict.enums.DictValueType;
import com.lj.dict.mapper.DictItemMapper;
import com.lj.dict.param.DictItemPageParam;
import com.lj.dict.param.DictItemSaveParam;
import com.lj.dict.param.DictItemUpdateParam;
import com.lj.dict.result.DictItemInfoResult;
import com.lj.dict.result.DictItemPageResult;
import com.lj.dict.result.DictItemResult;
import com.lj.dict.service.DictItemService;
import com.lj.dict.service.DictService;
import com.lj.mp.standard.StandardServiceImpl;
import com.lj.mp.utils.PageQueryUtils;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 字典项表 服务实现类
 * </p>
 *
 * @author luojing
 * @since 2025-01-10 11:16:54
 */
@Service
public class DictItemServiceImpl extends StandardServiceImpl<DictItemMapper, DictItem> implements DictItemService {


    @Resource
    @Lazy
    private DictService dictService;
    @Resource
    private RedisUtil redisUtil;

    @Override
    public IPage<DictItemPageResult> page(DictItemPageParam param) {
        return this.page(PageQueryUtils.getPage(param), getQueryWrapper(param)).convert(DictItemPageResult::of);
    }

    private LambdaQueryWrapper<DictItem> getQueryWrapper(DictItemPageParam param) {
        CheckUtils.ifNull(param.getDictId(), "字典id为必填项");
        return lambdaQueryWrapper()
                .eq(DictItem::getDictId, param.getDictId())
                .eq(ObjectUtil.isNotEmpty(param.getLabel()), DictItem::getLabel, param.getLabel())
                .eq(ObjectUtil.isNotEmpty(param.getValue()), DictItem::getValue, param.getValue())
                ;
    }

    @Override
    public DictItemInfoResult info(Long id) {
        return DictItemInfoResult.of(this.getById(id));
    }

    @Override
    public void save(DictItemSaveParam param) {
        DictItem entity = param.toEntity();
        verifyDictItem(entity);
        this.save(entity);
        this.clearCache(Collections.singletonList(entity.getDictId()));
    }

    @Override
    public void update(DictItemUpdateParam param) {
        DictItem entity = param.toEntity();
        verifyDictItem(entity);
        this.updateById(entity);
        this.clearCache(Collections.singletonList(entity.getDictId()));
    }

    @Override
    public void deleteByDictIds(List<Long> dictIds) {
        if (CollUtil.isEmpty(dictIds)) {
            return;
        }
        remove(lambdaQueryWrapper()
                .in(DictItem::getDictId, dictIds));
        this.clearCache(dictIds);
    }

    private void verifyDictItem(DictItem entity) {
        DictValueType valueType = entity.getValueType();
        CheckUtils.ifNull(valueType, "请选择正确的字典值类型");
        CheckUtils.ifCondition(!valueType.isValueType(entity.getValue()), "字典值类型与字典值类型不匹配");
        if (StrUtil.isNotBlank(entity.getExtendJson())) {
            // 如果附加信息不为空需要判断是否为json
            CheckUtils.ifCondition(!DictValueType.JSON.isValueType(entity.getExtendJson()), "请检测附加信息Json格式是否正确!");
        }
    }

    private void clearCache(List<Long> dictIds) {
        if (CollUtil.isEmpty(dictIds)) {
            return;
        }
        List<Dict> dictList = dictService.listByIds(dictIds);
        String[] cacheKeys = dictList.stream().map(dict -> DictConstant.DICT_TYPE_CACHE + dict.getDictType()).toArray(String[]::new);
        redisUtil.delete(cacheKeys);
    }

    @Override
    public List<DictItemResult<Object>> getDictItem(Dict dict) {
        if (dict == null) {
            return Collections.emptyList();
        }
        List<DictItem> dictItemList = getByDictId(dict.getId());
        if (CollUtil.isEmpty(dictItemList)) {
            return Collections.emptyList();
        }
        List<DictItemResult<Object>> dictItemResultList = new ArrayList<>();
        for (DictItem dictItem : dictItemList) {
            DictItemResult<Object> dictItemResult = new DictItemResult<>();
            dictItemResult.setLabel(dictItem.getLabel());
            dictItemResult.setValue(dictItem.getValueType().parseValueType(dictItem.getValue()));
            String extendJson = dictItem.getExtendJson();
            if (StrUtil.isNotBlank(extendJson)) {
                dictItemResult.setExtendJson(JSONUtil.parseObj(extendJson));
            }
            dictItemResultList.add(dictItemResult);
        }
        return dictItemResultList;
    }
}
